package day27;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server3 {
    //用于保存进入聊天室的客户端对象
    static List<Socket> sockets = new ArrayList<Socket>();
    static List<String> ID = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("多人聊天室");
        while (true) {
            Socket socket = serverSocket.accept();
            sockets.add(socket);
            System.out.println("聊天室:"+sockets.size()+"人");
            new Server3Thread(socket).start();
        }
    }
}

class Server3Thread extends Thread {
    Socket client;
    public Server3Thread(Socket client) {
        this.client = client;
    }
    public void run(){
        //读取当前客户端给我写的数据
        try {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(client.getInputStream()));
            while (true){
                String s = in.readLine();
                System.out.println(client.getInetAddress()+":"+s);
                String[] sd = s.split("请求私聊:");
                //退出聊天室
                if(s.contains("退出")){
                    Server3.sockets.remove(client);
                    System.out.println("聊天室:"+Server3.sockets.size()+"人");
                    return;//结束线程
                }

                //私聊
                if(s.contains("私聊")){
                    for (Socket c :Server3.sockets){
                        if (c!=client){
                            OutputStream os = c.getOutputStream();
                            os.write((s+"\n").getBytes());
                        }
                    }
                    return;//结束线程
                }

                //向其他客户端写入（发送）
                for (Socket c :Server3.sockets){
                    if (c!=client){
                        OutputStream os = c.getOutputStream();
                        os.write((s+"\n").getBytes());
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

//私聊线程
class Server3Thread1 extends Thread{

}
